from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render, redirect


# Create your views here.
from django.urls import reverse
from django.views import View


class LoginView(View):
    '''登录'''

    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        """登录校验"""
        username = request.POST.get('login_name', None)
        password = request.POST.get('password', None)
        if not all([username, password]):
            ctx = {}
            ctx['message'] = '参数错误'
            return render(request, 'login.html', ctx)
        user = authenticate(username=username, password=password)
        if user is not None:
            login(request, user)
            return redirect(reverse('index'))
        else:
            ctx = {}
            ctx['message'] = '账号密码错误，登录失败!'
            return render(request, 'login.html', ctx)


class LogoutView(View):

    def get(self, request):
        logout(request)
        return redirect(reverse('user:login'))
